﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Sistem
{
    public partial class Takimlar : XForm
    {
        public Takimlar()
        {
            InitializeComponent();
        }

        int TakimId = 0;
        private void Takimlar_Load(object sender, EventArgs e)
        {
            gleTakim.Edit.Assign(RI(Rp.Takim));
            gleTakim.EditValueChanged += gleTakim_EditValueChanged;
            btnKaydet.ItemClick += btnKaydet_ItemClick;
            gridView3.CustomDrawColumnHeader += gridView3_CustomDrawColumnHeader;

            DataRow[] r = AppSession.Lookups.Takim.Select("TeamLeaderId=" + WhoAmI.ToStr());
            if (r.Length > 0)
            {
                int TakimId = r[0]["TakimId"].ToInt();
                gleTakim.EditValue = TakimId;
                gleTakim.Enabled = false;
            }
        }

        private void gridView3_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && !e.Column.Visible)
            {
                return;
            }
            DrawVertical(e);
        }

        private static void DrawVertical(DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e)
        {
            Rectangle r;
            r = e.Info.CaptionRect;
            e.Info.Caption = string.Empty;
            e.Painter.DrawObject(e.Info);
            if (e.Column != null)
            {
                var state = e.Graphics.Save();
                var sf = new StringFormat();
                sf.Trimming = StringTrimming.EllipsisCharacter;
                sf.FormatFlags |= StringFormatFlags.NoWrap;
                sf.FormatFlags |= StringFormatFlags.DirectionVertical;
                e.Graphics.DrawString(e.Column.GetTextCaption(), e.Appearance.Font, e.Appearance.GetForeBrush(e.Cache), r, sf);
                e.Graphics.Restore(state);
            }
            e.Handled = true;
        }

        public static void SetBestHeaderHeight(GridView view)
        {
            view.BeginUpdate();
            foreach (GridColumn col in view.VisibleColumns)
            {
                int height = GetVerticalTextHeight(view, col.Caption) + 8;
                view.ColumnPanelRowHeight = Math.Max(height, view.ColumnPanelRowHeight);
            }
            view.EndUpdate();
        }

        private static int GetVerticalTextHeight(GridView view, string text)
        {
            DevExpress.Utils.AppearanceObject app = view.PaintAppearance.HeaderPanel;
            StringFormat sf = new StringFormat();
            sf.FormatFlags = StringFormatFlags.DirectionVertical;
            SizeF size = view.GridControl.CreateGraphics().MeasureString(text, app.GetFont(), 1000, sf);
            return size.ToSize().Height;
        }


        void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView3.EndEditing();

            //gridView1.Update("CustomerId, TakimId, CountryId, PrfShipMethodId, PrfPaymentTermId, Username, Password", "Customer");
            //gridView2.Update("UserId, DepartmentId, Bolum, Unvan, TakimId, Gender, Email, Notes", "[User]");

            string cust = string.Empty;
            foreach (DataRow r in d.Tables[0].Rows)
                cust += r["CustomerId"].ToStr() + ",";

            string usr = string.Empty;
            foreach (DataRow r in d.Tables[1].Rows)
                usr += r["UserId"].ToStr() + ",";

            DataTable matrix = new DataTable("Matrix");
            matrix.Columns.Add("CustomerId", typeof(int));
            matrix.Columns.Add("UserId", typeof(int));

            foreach (DataRow r in gridView3.DataTable().Rows)
                foreach (DataColumn c in gridView3.DataTable().Columns)
                    if (c.ColumnName != "CustomerId")
                        if (r[c.ColumnName] != null)
                            if (r[c.ColumnName] != DBNull.Value)
                                if (r[c.ColumnName].ToStr() != string.Empty)
                                    matrix.Rows.Add(r["CustomerId"].ToInt(), c.ColumnName.ToInt());

            string a = matrix.SerializeChanges();
            string b = matrix.Serialize();
            if (a == b)
            {
                a = b;
            }

            ExecuteNonQuery("UpdEmpCust",WhoAmI, cust, usr, matrix.Serialize());
        }

        void gleTakim_EditValueChanged(object sender, EventArgs e)
        {
            Rfrsh();
        }

        DataSet d;
        private void Rfrsh()
        {
            TakimId = gleTakim.EditValue.ToInt();
            d = ExecuteDataSet("GetTakimlar", TakimId);

            DataTable matrix = new DataTable("Matrix");
            matrix.Columns.Add("CustomerId", typeof(int));

            List<string> xusers = new List<string>();
            foreach (DataRow r in d.Tables[1].Rows)
            {
                xusers.Add("IIF([" + r["UserId"].ToStr() + "]='x', 1, 0)");
                matrix.Columns.Add(r["UserId"].ToStr(), typeof(string));
            }

            foreach (DataRow r in d.Tables[0].Rows)
            {
                DataRow r2 = matrix.NewRow();
                r2["CustomerId"] = r["CustomerId"];
                matrix.Rows.Add(r2);
            }
            matrix.SetPK("CustomerId"); //Find çalışsın diye!

            foreach (DataRow r in d.Tables[2].Rows)
                matrix.Rows.Find(r["CustomerId"].ToInt())
                    [r["UserId"].ToStr()] = "x";



            

            gridView3.Init(matrix);
            gridView3.AddColumn("toplam", typeof(int), String.Join("+", xusers.ToArray()));
            gridView3.FormatAsNumber(0, "toplam");
            gridView3.AddSummary();

            foreach (DataRow r in d.Tables[1].Rows)
                gridView3.SetCaptions(r["UserId"].ToStr() + ":" + AppSession.Lookups.V_User.FindByUserId(r["UserId"].ToInt()).Name);

            gridView3.MakeEditable("CustomerId");

            gridView3.BestFitColumns();
            foreach (GridColumn col in gridView3.Columns)
                if (col.FieldName != "CustomerId")
                    col.Width = 34;

            SetBestHeaderHeight(gridView3);

            gridView3.MouseMove -= gridView3_MouseMove;
            gridView3.MouseMove += gridView3_MouseMove;
        }


        int rowHandle;
        GridColumn column;

        void gridView3_MouseMove(object sender, MouseEventArgs e)
        {
            var hitInfo = gridView3.CalcHitInfo(e.Location);
            if (hitInfo != null)
            {
                Notify(" ");
                column = hitInfo.Column;
                rowHandle = hitInfo.RowHandle;
                if (column != null)
                    if (column.FieldName.ToInt() > 0)
                        if (rowHandle > -1)
                            Notify(AppSession.Lookups.V_Customer.FindByCustomerId(gridView3.GetDataRow(rowHandle)["CustomerId"].ToInt()).Name + 
                            (gridView3.GetDataRow(rowHandle)[column.FieldName].ToStr() != string.Empty ? " + " : " . ") +
                            AppSession.Lookups.V_User.FindByUserId(column.FieldName.ToInt()).Name);

            }
        }
    }
}
